<template>
  <Modal class="w-3/5" title="选择小区所在位置">
    <!-- 地图容器 -->
    <tlbs-map
      ref="mapRef"
      api-key="O7CBZ-4BJKZ-Q7CXH-7YY24-NMO42-P4BJ2"
      :center="center"
      :zoom="zoom"
      :control="control"
      @click="handleMapClick"
      @map_inited="onMapInited"
    >
      <tlbs-multi-marker :markers="markers" />
      <tlbs-multi-marker
        ref="markerRef"
        :geometries="geometries"
        :styles="styles"
        :options="options"
      />
    </tlbs-map>
    <!-- 显示选择的坐标 -->
    <div v-if="selectedCoordinate" class="coordinate-display">
      选择的坐标: {{ selectedCoordinate.lat }}, {{ selectedCoordinate.lng }}
    </div>
  </Modal>
</template>

<script lang="ts" setup>
defineOptions({
  name: 'MapModel',
});
import { ref, computed } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { useThrottleFn } from '@vueuse/core';
import { message } from 'ant-design-vue';

const emit = defineEmits(['success']);

// 弹窗标题
const mapRef = ref<any>(null);
const info = ref({});

const center = ref([39.9042, 116.4074]); // 初始中心点坐标（北京）
const zoom = ref(14); // 初始缩放级别
const selectedCoordinate = ref<any>(null); // 存储当前选择的坐标
const markers = ref<any[]>([]); // 存储标记点的数组（只有一个标记点）

const control = ref({
  scale: {},
  zoom: {
    position: 'topRight',
  },
});
const options = ref({
  renderOptions: {
    renderOptions: true,
  },
});
// 处理地图点击事件
const handleMapClick = (event: any) => {
  const lat = event.latlng.lat;
  const lng = event.latlng.lng;

  // 更新当前选择的坐标
  selectedCoordinate.value = { lat, lng };

  // 更新标记点数组（只保留一个标记点）
  markers.value = [
    {
      lat,
      lng,
      title: `标记点`, // 标记点标题
      content: `坐标: ${lat.toFixed(4)}, ${lng.toFixed(4)}`, // 标记点内容
    },
  ];

  console.log('Selected Coordinate:', selectedCoordinate.value);
  console.log('Markers:', markers.value);
};

const onMapInited = () => {
  // 地图加载完成后，可以获取地图实例，调用地图实例方法
  console.log(mapRef?.value.map);
};

const [Modal, modalApi] = useVbenModal({
  draggable: true,
  // fullscreen: true,
  // onConfirm: () => formApi.submitForm(),
});

//  提交
// const onSubmit = useThrottleFn(async (values: Record<string, any>) => {
//   const { valid } = await formApi.validate();
//   if (!valid) return;
//   let query = info.value?.dictId ? dictEdit : dictSave;
//   let res: any = await query({ ...values });
//   console.log(res);
//   message.success(res.message);
//   modalApi.close();
//   emit('success');
// }, 1000);

// 打开弹窗
const open = (data: any) => {
  // formApi.resetForm();
  // formApi.setValues(data);
  info.value = data;
  modalApi.open();
};

defineExpose({
  open,
});
</script>

<style lang="scss" scoped>
.control-container {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1001;
  display: flex;
  align-items: center;
}
button {
  padding: 4px;
  background-color: #fff;
  margin-right: 5px;
  border: 1px solid #ddd;
}
</style>
